package com.book.auth.filter;

import com.alibaba.fastjson.JSON;
import com.book.auth.JwtUtil;
import com.book.core.enums.REnum;
import com.book.core.mode.R;
import com.book.core.mode.SysLoginUser;
import io.jsonwebtoken.Claims;
import io.jsonwebtoken.ExpiredJwtException;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;

@Component
@RequiredArgsConstructor
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private final RedisTemplate<String, String> redisTemplate;

    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain)
            throws ServletException, IOException {

        // 1. 获取并校验Token
        String token = extractToken(request);
        if (!StringUtils.hasText(token)) {
            filterChain.doFilter(request, response);
            return;
        }

        // 2. 解析Token
        Claims claims;
        try {
            claims = JwtUtil.parseJWT(token);
        } catch (ExpiredJwtException e) {
            handleUnauthorized(response, R.err(REnum.TOKEN_EXPIRED));
            return;
        } catch (Exception e) {
            handleUnauthorized(response, R.err(REnum.TOKEN_INVALID));
            return;
        }
        // 3. 从Redis获取用户信息（含权限）
        SysLoginUser loginUser = getLoginUserFromRedis(claims.getSubject());
        if (loginUser == null) {
            handleUnauthorized(response, R.err(REnum.USER_NOT_LOGIN));
            return;
        }
        // 4. 由于springsecurity会将权限数据保存在session中，本项目禁用了session，需要每次请求重新构建Authentication（恢复权限）
        UsernamePasswordAuthenticationToken authentication =
                new UsernamePasswordAuthenticationToken(
                        loginUser,
                        null,
                        loginUser.getAuthorities()
                );
        // 5. 存入SecurityContext
        SecurityContextHolder.getContext().setAuthentication(authentication);
        // 6. 放行请求
        filterChain.doFilter(request, response);
    }

    // 从请求头提取Token（兼容Bearer前缀）
    private String extractToken(HttpServletRequest request) {
        String bearerToken = request.getHeader("Authorization");
        if (StringUtils.hasText(bearerToken) && bearerToken.startsWith("Bearer ")) {
            return bearerToken.substring(7);
        }
        return bearerToken;
    }

    // 从Redis获取用户信息
    private SysLoginUser getLoginUserFromRedis(String userId) {
        String redisKey = "loginUser:" + userId;
        String userJson = redisTemplate.opsForValue().get(redisKey);
        if (!StringUtils.hasText(userJson)) {
            return null;
        }
        return JSON.parseObject(userJson, SysLoginUser.class);
    }

    // 统一处理未授权响应
    private void handleUnauthorized(HttpServletResponse response, R r) throws IOException {
        response.setStatus(HttpServletResponse.SC_OK);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JSON.toJSONString(r));
    }
}
